<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 砖圈圈
 -->

<template>
  <div>
    <van-form class="brick-circle">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.cellphone"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(bind, index) in bindInfo" :key="index" center :title="bind.account">
        <template #right-icon>
          <van-switch
            v-model="bind.status"
            active-color="#e4393c"
            size="24"
            @change="onChange(bind)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import * as brick from "@/api/brick-circle";
// import * as api from "@/api/index";
import { JSEncrypt } from "jsencrypt";
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "BrickCircle",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        cellphone: "18870930124",
        password: "123456zqh",
        system_type: "android",
        ip_mac: window.api.deviceId,
        ver: "2.0.0.202005300"
      },
      // 循环时间
      IntervalTime: 30,
      // 任务类型
      type: "0",
      typeOptions: [{ label: "不接浏览单", type: "0" }],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      // 请求头
      headers: "",
      // verify
      verify: "",
      id: "",
      isaccept: "",
      show: false,
      bindInfo: [],
      public_key: "",
      time_stamp: "",
      unique_key: "",
      uuid: "",
      orderid: "",
      shop_name: "",
      buyprice: "",
      commission: "",
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 34 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,

          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.item.index === 34) {
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 34 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.cellphone = this.item.user;
        this.ruleForm.password = this.item.pass;
        // this.type = this.item.type || "0";

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 34 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.cellphone = this.item.user;
      this.ruleForm.password = this.item.pass;
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.headers = "";
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          headers: "",
          data: this.ruleForm
        };
        brick.ajaxFun(brick.getLogin, param, res => {
          if (res.code === 0) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.cellphone,
              pass: _this.ruleForm.password,
              type: _this.type,
              index: _this.index
            });
            _this.returnContent.unshift(alertMsg("登录成功"));
            _this.verify = res.data;
            _this.onGetMember(_this);
          } else {
            _this.returnContent.unshift(alertMsg(res.msg));
            _this.startFlag = false;
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 任务接单号
    onGetMember(_this) {
      _this.returnContent.unshift(alertMsg("正在获取接单号..."));
      _this.bindInfo = [];
      let param = {
        type: "get",
        headers: "",
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify
        }
      };
      brick.ajaxFun(brick.getMember, param, res => {
        if (res.code === 0) {
          // 选择接单号
          res.data.forEach(item => {
            if (item.isaccept === 1) {
              _this.bindInfo.push(item);
            }
          });
          if (_this.bindInfo.length === 1) {
            _this.onChange(_this.bindInfo[0]);
          } else {
            _this.show = true;
          }
        } else {
          _this.show = false;
          _this.startFlag = false;
        }
      });
    },
    // 选择账号
    onChange(data) {
      const _this = this;
      _this.show = false;
      _this.onGetCheckTbAccount(data, _this);
    },
    // 验证选择的账号
    onGetCheckTbAccount(data, _this) {
      let param = {
        type: "get",
        headers: "",
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify,
          platform_id: data.id,
          platform_type: 1,
          account: data.account
        }
      };
      brick.ajaxFun(brick.getCheckTbAccount, param, res => {
        if (res.code === 0) {
          _this.returnContent.unshift(
            alertMsg("接单号: " + data.account + "即将开始接单，请等待...")
          );
          let param = {
            type: "get",
            headers: "",
            data: {
              ver: "2.0.0.202005300",
              verify: _this.verify,
              id: data.id,
              isaccept: data.isaccept
            }
          };
          brick.ajaxFun(brick.getAccept, param, res => {
            if (res.code === 0) {
              _this.returnContent.unshift(alertMsg("正在卖力为您接单中..."));
              // 获取token
              _this.orderid = "";
              setTimeout(() => {
                if (_this.startFlag) {
                  _this.onGetAuth(_this);
                }
              }, _this.IntervalTime * 1000);
            } else {
              _this.returnContent.unshift(alertMsg(res.msg));
              _this.startFlag = false;
            }
          });
        } else {
          _this.returnContent.unshift(alertMsg(res.msg));
          _this.startFlag = false;
        }
      });
    },
    // 获取token
    onGetAuth(_this) {
      clearInterval(_this.timer);
      _this.uuid = _this.onGetUuid() + _this.onGetUuid();
      let param = {
        type: "get",
        headers: "",
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify,
          uuid: _this.uuid
        }
      };
      brick.ajaxFun(brick.getAuth, param, res => {
        if (res.code === 0) {
          // 匹配订单
          _this.public_key = res.data.public_key;
          _this.time_stamp = res.data.time_stamp;
          _this.unique_key = res.data.unique_key;
          if (_this.orderid != "") {
            _this.onGetSureOrderV2(_this);
          } else {
            _this.onGetAcceptV2(_this);
          }
        }
      });
    },
    // 生成 uuid
    onGetUuid() {
      return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
    },
    // 匹配订单
    onGetAcceptV2(_this) {
      let token = _this.encryptedData(
        _this.public_key,
        JSON.stringify({
          encrypt: _this.unique_key
        })
      );
      let param = {
        type: "get",
        headers: {
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify,
          uuid: _this.uuid,
          token: token
        }
      };
      _this.orderid = "";
      brick.ajaxFun(brick.getAcceptV2, param, res => {
        if (res.code == 0) {
          // 匹配订单
          if (
            res.data != "" &&
            res.data != null &&
            res.data != undefined &&
            JSON.stringify(res.data) != "{}"
          ) {
            if (res.data.accept_code == 1) {
              _this.timer = setInterval(() => {
                if (_this.startFlag) {
                  _this.onGetAuth(_this);
                }
              }, _this.IntervalTime * 1000);
            } else if (res.data.accept_code == 10010) {
              _this.returnContent.unshift(alertMsg(res.data.msg));
              _this.startFlag = false;
            } else {
              _this.orderid = res.data.orderid;
              _this.shop_name = res.data.shop_name;
              _this.buyprice = res.data.buyprice;
              _this.commission = res.data.commission;
              if (_this.type == 0 && res.data.tasktype == 100) {
                _this.returnContent.unshift(alertMsg("不接浏览单，跳过..."));
                _this.onGetNoOrder(_this);
              } else {
                _this.onGetAuth(_this);
              }
            }
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetAuth(_this);
              }
            }, _this.IntervalTime * 1000);
          }
        } else if (res.code == 1) {
          _this.returnContent.unshift(
            alertMsg("防封, 自动休息下，不要和平台App一起接单...")
          );
          return false;
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetAuth(_this);
            }
          }, _this.IntervalTime * 1000);
        }
      });
    },
    // 跳过浏览单
    onGetNoOrder(_this) {
      let param = {
        type: "get",
        headers: {
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify,
          orderid: _this.orderid,
          today_not_shop: 1
        }
      };
      brick.ajaxFun(brick.getNoOrder, param, res => {
        if (res.code === 0) {
          // 重新获取token
          _this.returnContent.unshift(alertMsg("正在卖力为您接单中..."));
          setTimeout(() => {
            _this.orderid = "";
            _this.onGetAuth(_this);
          }, _this.IntervalTime * 1000);
        } else {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetNoOrder(_this);
            }
          }, _this.IntervalTime * 1000);
        }
      });
    },
    // 确认接单
    onGetSureOrderV2(_this) {
      let token = _this.encryptedData(
        _this.public_key,
        JSON.stringify({
          encrypt: _this.unique_key
        })
      );
      let data = _this.encryptedData(
        _this.public_key,
        JSON.stringify({
          orderid: _this.orderid
        })
      );
      let param = {
        type: "get",
        headers: {
          "X-Requested-With": "XMLHttpRequest"
        },
        data: {
          ver: "2.0.0.202005300",
          verify: _this.verify,
          token: token,
          uuid: _this.uuid,
          data: data
        }
      };
      brick.ajaxFun(brick.getSureOrderV2, param, res => {
        if (res.code === 0) {
          _this.orderid = "";
          _this.returnContent.unshift(
            alertMsg(
              " 付款金额：" +
                _this.buyprice +
                " 佣金: " +
                _this.commission +
                " 店铺名称: " +
                _this.shop_name
            )
          );
          _this.returnContent.unshift(alertMsg("接单成功"));
          _this.returnContent.unshift(alertMsg("做完任务后请手动点击开始接单"));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ["接单成功，请前往做单..."]
          });
        } else {
          _this.orderid = "";
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetAuth(_this);
            }
          }, _this.IntervalTime * 1000);
        }
      });
    },
    encryptedData(publicKey, data) {
      var n = "-----BEGIN PUBLIC KEY-----\r\n";
      n += publicKey;
      n += "\r\n-----END PUBLIC KEY-----";
      // 新建JSEncrypt对象
      let encryptor = new JSEncrypt();
      // 设置公钥
      encryptor.setPublicKey(n);
      // 加密数据
      return encryptor.encrypt(data);
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>
